package com.sdp.th.task;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdp.core.bizc.utils.ApplicationContextUtils;
import com.sdp.right.cron.ScheduledOfTask;
import com.sdp.right.db.sys_config.service.ISysConfigService;
import com.sdp.right.entity.SysConfig;
import com.sdp.th.db.th_eq_power.service.IThEqPowerService;
import com.sdp.th.db.th_eq_state.service.impl.ThEqStateServiceImpl;
import com.sdp.th.entity.ThEqPower;
import com.sdp.th.view.ThEqStateView;

@Component
public class ThPowerEqTask implements ScheduledOfTask{
	
	@Autowired
	private IThEqPowerService iThEqPowerService;
	
	@Autowired
	private ThEqStateServiceImpl thEqStateServiceImpl;

	@Override
	@Transactional(rollbackFor=Exception.class)
	public void execute() {
		BigDecimal lowPower = BigDecimal.valueOf(20);
		SysConfig thConfig = ApplicationContextUtils.getBean(ISysConfigService.class).querySysConfigByParamCode("4443025736215187456");
		
		if(thConfig!=null) {
			lowPower = new BigDecimal(thConfig.getParamVal());
		}
		
		//先删除所有低电量设备信息
		iThEqPowerService.removeAll();
		
	
		QueryWrapper<ThEqStateView> queryWrapper = new QueryWrapper<ThEqStateView>();
		List<ThEqStateView> eqStateList = thEqStateServiceImpl.viewList(queryWrapper, null);
		List<ThEqPower> powerList = new ArrayList<ThEqPower>();
		for(ThEqStateView state : eqStateList) {
			if(state.getDevicePower().compareTo(lowPower)<0) {
				ThEqPower power = new ThEqPower();
				power.setDeviceNo(state.getDeviceNo());
				power.setCreateTime(LocalDateTime.now());
				power.setDeviceType(state.getDeviceType());
				power.setDeviceName(state.getDeviceName());
				power.setDeviceRegion(state.getDeviceRegion());
				power.setDeviceRoom(state.getDeviceRoom());
				powerList.add(power);
			}
		}
		
		if(powerList.size()>0) {
			iThEqPowerService.saveBatch(powerList);
		}
		
	}
}
